package com.shihan.redis.springboot.demo.service.impl;

import com.shihan.redis.springboot.demo.entity.OrderNumberEntity;
import com.shihan.redis.springboot.demo.enums.OrderStatusEnum;
import com.shihan.redis.springboot.demo.mapper.OrderMapper;
import com.shihan.redis.springboot.demo.service.OrderService;
import com.shihan.redis.springboot.demo.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @Description
 * @Author shihan
 * @Date 2021/1/23 20:25
 * @Version 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public boolean createOrder(String orderName) {
        OrderNumberEntity orderNumberEntity = new OrderNumberEntity();
        String orderToken = UUID.randomUUID().toString();
        // 刚创建的订单，状态为 0-未支付，1-已支付，2-已废弃
        orderNumberEntity.setOrderStatus(OrderStatusEnum.ORDER_UN_PAY.getValue());
        orderNumberEntity.setOrderToken(orderToken);
        orderNumberEntity.setOrderName(orderName);
        orderNumberEntity.setOrderId("ORDER_ID_" + System.currentTimeMillis() + "_" + orderName);
        System.out.println("订单信息为：" + orderNumberEntity);

        int order = orderMapper.createOrder(orderNumberEntity);
        if (order > 0) {
            System.out.println("订单创建成功！");
            setOrderTokenExpire(orderNumberEntity);
            System.out.println("订单有效期设置成功！");
        }

        return true;
    }

    @Override
    public boolean payOrder(String orderId) {
        OrderNumberEntity orderNumberEntity = new OrderNumberEntity();
        // 0-未支付，1-已支付，2-已废弃
        orderNumberEntity.setOrderStatus(OrderStatusEnum.ORDER_PAYED.getValue());
        orderNumberEntity.setOrderId(orderId);

        System.out.println(orderNumberEntity);

        int res = orderMapper.updateOrderStatus(orderNumberEntity);

        if (res > 0) {
            System.out.println("订单支付状态更新成功！");
            return true;
        }

        return false;
    }

    /**
     * 给订单设置过期时间，通过 order_token 进行关联（模拟超时时间为 30 秒）
     * 需要 orderToken 和 OrderId
     *
     * @param orderNumberEntity
     * @return
     */
    private boolean setOrderTokenExpire(OrderNumberEntity orderNumberEntity) {

        redisUtils.setString(orderNumberEntity.getOrderToken(), orderNumberEntity.getOrderId(), 30L);

        System.out.println("过期时间设置为 30 秒！");

        return true;
    }
}
